package alipaylogic

import (
	"context"
	"encoding/json"
	"io/ioutil"
	"log"
	"yundian/internel/app/dao"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/pkg/alipayex"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

type AlipayBaseLogic struct {
	WxConfig   *paysetting.PaySetting
	Client     *alipayex.Client
	PrivateKey string
}

func newAlipayBaseLogic() (*AlipayBaseLogic, error) {
	wxConfig := GetPaySettingByTypeName(global.Cfg.Ali.PayTypeName)
	file, err := ioutil.ReadFile(global.Cfg.Ali.PrivateKey)

	if err != nil {
		return &AlipayBaseLogic{}, err
	}

	AppCert, err := alipayex.GetCertSN(global.Cfg.Ali.AppCert)
	AliPayPublicCert, err := alipayex.GetCertSN(global.Cfg.Ali.AliPayPublicCert)
	AliPayRootCert, err := alipayex.GetRootCertSN(global.Cfg.Ali.AliPayRootCert)
	client, _ := alipayex.NewClient(wxConfig.AppId, string(file), true)
	client.SetCharset("utf-8").
		SetSignType(alipayex.RSA2).
		SetPrivateKeyType(alipayex.PKCS1).
		SetAppCertSN(AppCert).
		SetAliPayPublicCertSN(AliPayPublicCert).
		SetAliPayRootCertSN(AliPayRootCert)

	return &AlipayBaseLogic{WxConfig: wxConfig, PrivateKey: string(file), Client: client}, nil
}

func GetPaySettingByTypeName(typeName string) *paysetting.PaySetting {
	var settInfo *paysetting.PaySetting
	// 判断redis中是否存在
	s := global.Rdb.Get(context.Background(), utils.Join(typeName, "-paysetting")).Val()
	if s == "" {
		settInfo = dao.NewSiteSettingDao().GetPaySettingInfoByTypeName(typeName).Unwrap().(*paysetting.PaySetting)
		global.Rdb.Set(context.Background(), utils.Join(typeName, "-paysetting"), settInfo, 0)
	} else {
		_ = json.Unmarshal([]byte(s), &settInfo)
	}
	log.Println("打印测试信息---配置", settInfo, settInfo.MchId)
	return settInfo
}
